const WXAPI = require('apifm-wxapi')
const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
import ApifmShare from '../../template/share/index.js';
const CONFIG = require('../../config.js')
const AUTH = require('../../utils/auth')
const SelectSizePrefix = "选择："
const SETGOODS = require('../../utils/setgoos.js');

let videoAd = null; // 视频激励广告

Page({
  data: {
    goodsDetail: {},
    hasMoreSelect: false,
    selectSize: SelectSizePrefix,
    selectSizePrice: 0,
    totalScoreToPay: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,

    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    selItem:{},//默认选中规格
  },
  async onLoad(e) {
    ApifmShare.init(this)
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene) // 处理扫码进商品详情页面的逻辑
      if (scene) {
        e.id = scene.split(',')[0]
        wx.setStorageSync('referrer', scene.split(',')[1])
      }
    }
    console.log('e-0-',e)
    // this.data.goodsId = e.id
    // this.data.kjJoinUid = e.kjJoinUid
    const that = this;
    this.setData({
      goodsId: e.id,
      // kjJoinUid: e.kjJoinUid,
      shopNum: app.globalData.goodsNo,
    })
    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
        let list = res.data;
        that.setData({
          shopCarInfo: res.data,
          curuid: wx.getStorageSync('uid')
        });
      }
    })
  },
  // 获取购物车商品数量
  getGoodsNo(){
    let that = this;
    // 获取购物车数据
   
  },
  onShow (){
    this.getGoodsDetailAndKanjieInfo(this.data.goodsId)
  },
  async getGoodsDetailAndKanjieInfo(goodsId) {
    const that = this;
    const goodsDetailRes = await WXAPI.goodsDetail(goodsId)
    //const goodsKanjiaSetRes = await WXAPI.kanjiaSet(goodsId)
    if (goodsDetailRes.retCode == 200) {
      var selectSizeTemp = SelectSizePrefix;
      if (goodsDetailRes.data) {
        // for (var i = 0; i < goodsDetailRes.data.properties.length; i++) {
        //   selectSizeTemp = selectSizeTemp + " " + goodsDetailRes.data.properties[i].name;
        // }
        that.setData({
          hasMoreSelect: false,
          selectSize: selectSizeTemp,
          selectSizePrice: goodsDetailRes.data.price,
          //totalScoreToPay: goodsDetailRes.data.basicInfo.minScore
        });
      }

      let childs = goodsDetailRes.data;
      for (let [index, item] of childs.itemSkuResultDtos.entries()) {
        item.checked = false;
        item.value = index;
        item.text = item.stockTitle;
      }
      // 选中的规格
      childs.itemSkuResultDtos[0].checked = true;
      childs.value = 0; 
      childs.narrowPicUrl = childs.itemSkuResultDtos[0].narrowPicUrl; 
      
      let _data = {
        goodsDetail: goodsDetailRes.data,
        selItem: {
          price: goodsDetailRes.data.itemSkuResultDtos[0].price,
          narrowPicUrl: goodsDetailRes.data.itemSkuResultDtos[0].narrowPicUrl,
          stockTitle: goodsDetailRes.data.itemSkuResultDtos[0].stockTitle,
          stockNo: goodsDetailRes.data.itemSkuResultDtos[0].stockNo,
        },
        selectSizePrice: goodsDetailRes.data.price,
        //totalScoreToPay: goodsDetailRes.data.basicInfo.minScore,
        // buyNumMax: goodsDetailRes.data.stockNum,
        // buyNumber: (goodsDetailRes.data.stockNum > 0) ? 1 : 0
      }
      
       that.setData(_data);
    }
  },
  goShopCar: function() {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  // 加入购物车，选择数量规格
  toAddShopCar: function() {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  // 立即购买，选择数量规格
  tobuy: function() {
    this.setData({
      shopType: "tobuy",
      // selectSizePrice: this.data.price
    });
    this.bindGuiGeTap();
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function() {
    // if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    // }
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    /*
    console.log(e)
    console.log(e.currentTarget.dataset.propertyid)
    console.log(e.currentTarget.dataset.propertyname)
    console.log(e.currentTarget.dataset.propertychildid)
    console.log(e.currentTarget.dataset.propertychildname)
    */
    // console.log(e.currentTarget)
    let ind = e.currentTarget.dataset.index;
    let childs = that.data.goodsDetail;
    for (let [index ,item] of childs.itemSkuResultDtos.entries()){
      item.checked  = false;
      item.value = index;
      item.text = item.stockTitle;
      if (ind == index){
        childs.stockTitle = item.stockTitle;
        childs.narrowPicUrl = item.narrowPicUrl;
        childs.stockNo = item.stockNo;
        childs.price = item.price;
      }
    }
    // 选中的规格
    childs.itemSkuResultDtos[ind].checked = true;
    childs.value = ind;
    // 购物车选中标识
    childs.checked = false;
    
    that.setData({
      selItem: {
        price: childs.itemSkuResultDtos[ind].price,
        narrowPicUrl: childs.itemSkuResultDtos[ind].narrowPicUrl,
        stockTitle: childs.itemSkuResultDtos[ind].stockTitle,
        stockNo: childs.itemSkuResultDtos[ind].stockNo,
      },
      goodsDetail:childs,
    })

  },
  /**
   * 加入购物车
   */
  addShopCar: function() {
    let that = this;
    // if (this.data.goodsDetail.properties && !this.data.canSubmit) {
    //   if (!this.data.canSubmit) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '请选择商品规格！',
    //       showCancel: false
    //     })
    //   }
    //   this.bindGuiGeTap();
    //   return;
    // }
    // if (this.data.buyNumber < 1) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '购买数量不能为0！',
    //     showCancel: false
    //   })
    //   return;
    // }
    //组建购物车
    // var shopCarInfo = this.bulidShopCarInfo();

    // this.setData({
    //   shopCarInfo: shopCarInfo,
    //   shopNum: shopCarInfo.shopNum
    // });
    let goodsDetailObj = that.data.goodsDetail;
    goodsDetailObj.buyNumber = that.data.buyNumber;
    goodsDetailObj.price = that.data.selItem.price;
    goodsDetailObj.stockNo = that.data.selItem.stockNo;
    goodsDetailObj.stockTitle = that.data.selItem.stockTitle;

    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * (that.data.buyNumber);
    console.log(goodsDetailObj)
    
    SETGOODS.setGoods(goodsDetailObj, goodsDetailObj.itemNo, that.data.selItem.stockNo, goodsDetailObj.shopNo);
    this.getGoodsNo();
    // let shopCarInfo = goodsDetailObj; 
    // wx.getStorage({
    //   key: 'shopCarInfo',
    //   success: function(res) {
    //     let resArr = res.data;
    //     resArr.push(goodsDetailObj)
    //     wx.setStorage({
    //       key: 'shopCarInfo',
    //       data: resArr
    //     })
    //   },
    //   fail() {
    //     let resArr = [];
    //     resArr.push(goodsDetailObj)
    //     wx.setStorage({
    //       key: 'shopCarInfo',
    //       data: resArr
    //     })
    //   }
    // })

    // 写入本地存储
    
    this.closePopupTap();
    //写入数据库
    // console.log('-=-',shopCarInfo)
    // const postData = {
    //   "buyNum": "string",
    //   "itemNo": "string"
    // }
    // WXAPI.addShoppingCart
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000,
      success(){
        that.setData({
          shopNum: app.globalData.goodsNo,
        })
      }
    })
    //console.log(shopCarInfo);

    //shopCarInfo = {shopNum:12,shopList:[]}
  },
  /**
   * 立即购买
   */
  buyNow: function(e) {
    let that = this
    let shoptype = e.currentTarget.dataset.shoptype

    // if (this.data.goodsDetail.properties && !this.data.canSubmit) {
    //   if (!this.data.canSubmit) {
    //     wx.showModal({
    //       title: '提示',
    //       content: '请选择商品规格！',
    //       showCancel: false
    //     })
    //   }
    //   this.bindGuiGeTap();
    //   wx.showModal({
    //     title: '提示',
    //     content: '请先选择规格尺寸哦~',
    //     showCancel: false
    //   })
    //   return;
    // }
    // if (this.data.buyNumber < 1) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '购买数量不能为0！',
    //     showCancel: false
    //   })
    //   return;
    // }
    //组建立即购买信息
    // var buyNowInfo = this.buliduBuyNowInfo(shoptype);
    let goodsDetailObj = that.data.goodsDetail;
    goodsDetailObj.buyNumber = that.data.buyNumber;
    goodsDetailObj.price = that.data.selItem.price;
    goodsDetailObj.stockNo = that.data.selItem.stockNo;
    goodsDetailObj.stockTitle = that.data.selItem.stockTitle;
    goodsDetailObj.checked = true;

    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * (that.data.buyNumber);
    console.log(goodsDetailObj)

    let resArr = [{
      shopNo: goodsDetailObj.shopNo,
      shopName: goodsDetailObj.shopName,
      checked: false,
      list: []
    }]
    // console.log(goodsObj)
    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * goodsDetailObj.buyNumber;
    resArr[0].list.push(goodsDetailObj);

    SETGOODS.setBuyNowGoods(resArr);

    // 写入本地存储
    // wx.setStorage({
    //   key: "buyNowInfo",
    //   data: goodsDetailObj
    // })
    this.closePopupTap();
    wx.navigateTo({
      url: "/pages/to-pay-order/index?orderType=buyNow"
    })
    // if (shoptype == 'toPingtuan') {
    //   if (this.data.pingtuanopenid) {
    //     wx.navigateTo({
    //       url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + this.data.pingtuanopenid
    //     })
    //   } else {
    //     WXAPI.pingtuanOpen(wx.getStorageSync('token'), that.data.goodsDetail.basicInfo.id).then(function(res) {
    //       if (res.code == 2000) {
    //         wx.showModal({
    //           title: '提示',
    //           content: '本次操作需要您的登录授权',
    //           cancelText: '暂不登录',
    //           confirmText: '前往登录',
    //           success(res) {
    //             if (res.confirm) {
    //               wx.switchTab({
    //                 url: "/pages/my/index"
    //               })
    //             }
    //           }
    //         })
    //         return
    //       }
    //       if (res.code != 0) {
    //         wx.showToast({
    //           title: res.msg,
    //           icon: 'none',
    //           duration: 2000
    //         })
    //         return
    //       }
    //       wx.navigateTo({
    //         url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + res.data.id
    //       })
    //     })
    //   }
    // } else {
    //   wx.navigateTo({
    //     url: "/pages/to-pay-order/index?orderType=buyNow"
    //   })
    // }

  },


  /**
   * 组建购物车信息
   */
  bulidShopCarInfo: function() {
    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.goodsDetail.itemNo;
    shopCarMap.pic = this.data.goodsDetail.narrowPicUrl;
    shopCarMap.name = this.data.goodsDetail.itemTitle;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    //shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    //shopCarMap.logistics = this.data.goodsDetail.logistics;
    //shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    shopCarInfo.kjId = this.data.kjId;

    return shopCarInfo;
  },
  /**
   * 组建立即购买信息
   */
  buliduBuyNowInfo: function(shoptype) {
    var shopCarMap = {};
    console.log("buliduBuyNowInfo data=", this.data)
    shopCarMap.goodsId = this.data.goodsDetail.itemNo;
    shopCarMap.pic = this.data.goodsDetail.picUrl;
    shopCarMap.name = this.data.goodsDetail.itemTitle;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    // if (shoptype == 'toPingtuan') { // 20190714 拼团价格注释掉
    //   shopCarMap.price = this.data.goodsDetail.basicInfo.pingtuanPrice;
    // }
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    //shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
   // shopCarMap.logistics = this.data.goodsDetail.logistics;
    //shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    /*    var hasSameGoodsIndex = -1;
        for (var i = 0; i < toBuyInfo.shopList.length; i++) {
          var tmpShopCarMap = toBuyInfo.shopList[i];
          if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
            hasSameGoodsIndex = i;
            shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
            break;
          }
        }
        toBuyInfo.shopNum = toBuyInfo.shopNum + this.data.buyNumber;
        if (hasSameGoodsIndex > -1) {
          toBuyInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
        } else {
          toBuyInfo.shopList.push(shopCarMap);
        }*/

    buyNowInfo.shopList.push(shopCarMap);
    buyNowInfo.kjId = this.data.kjId;
    return buyNowInfo;
  },
  onShareAppMessage: function() {
    let _data = {
      title: this.data.goodsDetail.itemTitle,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.itemNo ,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
    // if (this.data.kjJoinUid) {
    //   _data.title = this.data.curKanjiaprogress.joiner.nick + '邀请您帮TA砍价'
    //   _data.path += '&kjJoinUid=' + this.data.kjJoinUid
    // }
    return _data
  },
  reputation: function(goodsId) {
    var that = this;
    WXAPI.goodsReputation({
      goodsId: goodsId
    }).then(function(res) {
      if (res.code == 0) {
        that.setData({
          reputation: res.data
        });
      }
    })
  },
  pingtuanList: function(goodsId) {
    var that = this;
    WXAPI.pingtuanList({
      goodsId: goodsId,
      status: 0
    }).then(function(res) {
      if (res.code == 0) {
        that.setData({
          pingtuanList: res.data.result
        });
      }
    })
  },
  getVideoSrc: function(videoId) {
    var that = this;
    WXAPI.videoDetail(videoId).then(function(res) {
      if (res.code == 0) {
        that.setData({
          videoMp4Src: res.data.fdMp4
        });
      }
    })
  },
  joinKanjia(){
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        this.doneJoinKanjia();
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/my/index"
              })
            }
          }
        })
      }
    })
  },
  // doneJoinKanjia: function() { // 报名参加砍价活动
  //   const _this = this;
  //   if (!_this.data.curGoodsKanjia) {
  //     return;
  //   }
  //   wx.showLoading({
  //     title: '加载中',
  //     mask: true
  //   })
  //   WXAPI.kanjiaJoin(wx.getStorageSync('token'), _this.data.curGoodsKanjia.id).then(function(res) {
  //     wx.hideLoading()
  //     if (res.code == 0) {
  //       _this.data.kjJoinUid = wx.getStorageSync('uid')
  //       _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.basicInfo.id)
  //     } else {
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'none'
  //       })
  //     }
  //   })
  // },
  // joinPingtuan: function(e) {
  //   let pingtuanopenid = e.currentTarget.dataset.pingtuanopenid
  //   wx.navigateTo({
  //     url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + pingtuanopenid
  //   })
  // },
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  },
  // helpKanjia() {
  //   const _this = this;
  //   AUTH.checkHasLogined().then(isLogined => {
  //     if (isLogined) {
  //       if (CONFIG.kanjiaRequirePlayAd) {
  //         // 显示激励视频广告
  //         if (videoAd) {
  //           videoAd.show().catch(() => {
  //             // 失败重试
  //             videoAd.load()
  //               .then(() => videoAd.show())
  //               .catch(err => {
  //                 console.log('激励视频 广告显示失败')
  //               })
  //           })
  //         }
  //         return;
  //       } else {
  //         _this.helpKanjiaDone()
  //       }
  //     } else {
  //       app.goLoginPageTimeOut()
  //     }
  //   })
  // },
  // helpKanjiaDone(){
  //   const _this = this;
  //   WXAPI.kanjiaHelp(wx.getStorageSync('token'), _this.data.kjId, _this.data.kjJoinUid, '').then(function (res) {
  //     if (res.code != 0) {
  //       wx.showToast({
  //         title: res.msg,
  //         icon: 'none'
  //       })
  //       return;
  //     }
  //     _this.setData({
  //       myHelpDetail: res.data
  //     });
  //     wx.showModal({
  //       title: '成功',
  //       content: '成功帮TA砍掉 ' + res.data.cutPrice + ' 元',
  //       showCancel: false
  //     })
  //     _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.basicInfo.id)
  //   })
  // }
})